package com.agriculture.service.impl;

import com.agriculture.domain.Product;
import com.agriculture.exception.BusinessException;
import com.agriculture.mapper.ProductMapper;
import com.agriculture.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    private static final Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);

    @Override
    public Product getProductById(Long id) {
        Product product = productMapper.findById(id);
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }
        return product;
    }

    @Override
    public List<Product> findByCategory(String category) {
        return productMapper.findByCategory(category);
    }

    @Override
    public List<Product> findByOwner(Long ownerId, String ownerType) {
        return productMapper.findByOwner(ownerId, ownerType);
    }

    @Override
    @Transactional
    public Product createProduct(Product product) {
        // 打印接收到的数据
        logger.info("Service层接收到的商品数据详细信息:");
        logger.info("- 商品名称: {}", product.getProductName());
        logger.info("- 类型: {}", product.getType());
        logger.info("- 分类: {}", product.getCategory());
        logger.info("- 价格: {}", product.getPrice());
        logger.info("- 单位: {}", product.getUnit());
        logger.info("- 库存: {}", product.getStock());
        logger.info("- 状态: {}", product.getStatus());
        logger.info("- 所有者ID: {}", product.getOwnerId());
        logger.info("- 所有者类型: {}", product.getOwnerType());
        
        // 参数验证
        if (product.getProductName() == null || product.getProductName().trim().isEmpty()) {
            throw new RuntimeException("商品名称不能为空");
        }
        
        try {
            productMapper.insert(product);
            return product;
        } catch (Exception e) {
            logger.error("创建商品失败: {}", e.getMessage());
            throw new RuntimeException("创建商品失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public void updateStatus(Long productId, String status) {
        // 检查产品是否存在
        Product product = productMapper.findById(productId);
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }
        
        // 验证状态值是否有效
        if (!"on_sale".equals(status) && !"off_shelf".equals(status)) {
            throw new RuntimeException("无效的状态值");
        }
        
        // 执行状态更新
        int rows = productMapper.updateStatus(productId, status);
        if (rows != 1) {
            throw new RuntimeException("更新状态失败");
        }
    }

    @Override
    @Transactional
    public boolean updateStock(Long productId, Integer stock) {
        try {
            Product product = productMapper.findById(productId);
            if (product == null) {
                return false;
            }
            
            // 更新库存
            int rows = productMapper.updateStock(productId, stock);
            if (rows != 1) {
                return false;
            }
            
            // 如果库存为0且商品当前状态为在售，自动更新为售罄状态
            if (stock == 0 && "on_sale".equals(product.getStatus())) {
                productMapper.updateStatus(productId, "sold_out");
            }
            // 如果之前是售罄状态，且现在有库存了，自动恢复为在售状态
            else if (stock > 0 && "sold_out".equals(product.getStatus())) {
                productMapper.updateStatus(productId, "on_sale");
            }
            
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public List<Product> searchProducts(String keyword, String category) {
        // 如果需要搜索功能，需要在 ProductMapper 中添加对应的方法
        throw new RuntimeException("方法未实现");
    }

    @Override
    public List<Product> getProductsByPage(Long ownerId, 
                                         String ownerType, 
                                         String keyword, 
                                         String category, 
                                         Integer offset, 
                                         Integer pageSize) {
        logger.info("查询参数: ownerId={}, ownerType={}, keyword={}, category={}, offset={}, pageSize={}", 
            ownerId, ownerType, keyword, category, offset, pageSize);
            
        List<Product> products = productMapper.findProducts(ownerId, 
                                                          ownerType, 
                                                          keyword, 
                                                          category, 
                                                          offset, 
                                                          pageSize);
        logger.info("查询结果数量: {}", products.size());
        return products;
    }
    
    @Override
    public int getProductsCount(Long ownerId, 
                              String ownerType, 
                              String keyword, 
                              String category) {
        return productMapper.getProductsCount(ownerId, ownerType, keyword, category);
    }

    @Override
    @Transactional
    public Product updateProduct(Long productId, Product product) {
        // 检查产品是否存在
        Product existingProduct = productMapper.findById(productId);
        if (existingProduct == null) {
            throw new RuntimeException("商品不存在");
        }
        
        // 设置ID确保更新正确的记录
        product.setProductId(productId);
        
        // 保留一些不应该被更新的字段
        product.setOwnerId(existingProduct.getOwnerId());
        product.setOwnerType(existingProduct.getOwnerType());
        product.setStock(existingProduct.getStock());
        product.setStatus(existingProduct.getStatus());
        
        // 执行更新
        int rows = productMapper.update(product);
        if (rows != 1) {
            throw new RuntimeException("更新商品失败");
        }
        
        // 返回更新后的商品信息
        return productMapper.findById(productId);
    }

    @Override
    @Transactional
    public void deleteProduct(Long productId) {
        // 检查产品是否存在
        Product product = productMapper.findById(productId);
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }
        
        // 执行删除
        int rows = productMapper.delete(productId);
        if (rows != 1) {
            throw new RuntimeException("删除商品失败");
        }
    }
} 